package com.jack.cms.oss.service.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import com.jack.cms.oss.core.FileVO;
import com.jack.cms.oss.core.QiniuUtils;
import com.jack.cms.oss.core.UUIDUtil;
import com.jack.cms.oss.service.OssService;
import com.qiniu.storage.model.FileListing;

public abstract class OssServiceImpl implements OssService {
	
	protected abstract QiniuUtils getQiniuUtil();
	
	@Override
	public String save(MultipartFile fileUpLoad) throws Exception {
		String fileName = fileUpLoad.getOriginalFilename();
		String index = fileName.substring(fileName.lastIndexOf("."));
		// 文件名称
		String imageName = UUIDUtil.getUUID() + index;
		// 保存媒体图片部分
		InputStream is = fileUpLoad.getInputStream();
		byte[] buffer = IOUtils.toByteArray(is);
		ByteArrayInputStream bai = new ByteArrayInputStream(buffer);
		FileVO vo = new FileVO();
		vo.setFileSize(buffer.length / 1024);
		vo.setIn(bai);
		// 保存到物理存储
		return getQiniuUtil().upload(vo.getIn(), imageName);
	}

	@Override
	public FileListing list(String marker, int count) throws Exception {
		return getQiniuUtil().list(marker, count);
	}
	
	@Override
	public String getUrl(String fileName) throws Exception {
		return getQiniuUtil().getUrl(fileName);
	}
}
